package com.hippoDocker.security.service.impl;

import cn.hutool.core.convert.Convert;
import com.hippoDocker.commons.entities.CommonResult;
import com.hippoDocker.security.entity.UmsMember;
import com.hippoDocker.security.pojo.dto.LoginUserDTO;
import com.hippoDocker.security.service.LoginService;
import com.hippoDocker.security.service.RedisService;
import com.hippoDocker.security.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * @ClassName LoginServiceImpl
 * @Description TODO 用户登录
 * @Author tangxl
 * @Date 2022/7/26 19:48
 **/
@Service
public class LoginServiceImpl implements LoginService, Serializable {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisService redisService;

    @Override
    public CommonResult login(UmsMember umsMember) {
        // 调用AuthenticationManager的authenticate方法进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(umsMember.getUsername(), umsMember.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //认证未通过
        if (authentication == null) {
            return CommonResult.failed("登录失败！");
        }
        //认证通过 将Object强转为LoginUserDTO对应
        LoginUserDTO loginUserDTO = Convert.convert(LoginUserDTO.class,authentication.getPrincipal());
        //获取用户ID
        Long id = loginUserDTO.getUmsMember().getId();
        //生成JWT
        String jwt = JwtUtil.createJWT(id.toString(),null);
        loginUserDTO.getUmsMember().setToken(jwt);
        //把用户信息和生成的jwt放入redis
        redisService.set(loginUserDTO.getUmsMember().getId().toString(),jwt,2*60*60L);
        redisService.set("login:"+loginUserDTO.getUmsMember().getId().toString(),loginUserDTO, 2*60*60L);
        return CommonResult.success("登录成功！token：",loginUserDTO);
    }

    @Override
    public CommonResult logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUserDTO loginUserDTO = Convert.convert(LoginUserDTO.class,authentication.getPrincipal());
        //删除redis中的用户缓存信息
        boolean boo1 = redisService.del(loginUserDTO.getUmsMember().getId().toString());
        boolean boo2 = redisService.del("login:"+loginUserDTO.getUmsMember().getId().toString());
        if(boo1&&boo2){
            return CommonResult.success("注销成功");
        }
        return CommonResult.failed("注销失败");
    }
}
